import socket
import time

import requests
from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.schedulers.blocking import BlockingScheduler

import os

g_adsl_account = {"name": "宽带连接",
                  "username": "test",
                  "password": "Aa123456"}


class Adsl(object):
    # ==============================================================================
    # __init__ : name: adsl名称
    # ==============================================================================
    def __init__(self):
        self.name = g_adsl_account["name"]
        self.username = g_adsl_account["username"]
        self.password = g_adsl_account["password"]

    # ==============================================================================
    # set_adsl : 修改adsl设置
    # ==============================================================================
    def set_adsl(self, account):
        self.name = account["name"]
        self.username = account["username"]
        self.password = account["password"]

    # ==============================================================================
    # connect : 宽带拨号
    # ==============================================================================
    def connect(self):
        cmd_str = "rasdial %s %s %s" % (self.name, self.username, self.password)
        os.system(cmd_str)
        time.sleep(3)

    # ==============================================================================
    # disconnect : 断开宽带连接
    # ==============================================================================
    def disconnect(self):
        cmd_str = "rasdial %s /disconnect" % self.name
        os.system(cmd_str)
        time.sleep(2)

    # ==============================================================================
    # reconnect : 重新进行拨号
    # ==============================================================================
    def reconnect(self):
        self.disconnect()
        self.connect()
        # 是否连接上了
        if not self.is_connected():
            self.reconnect()


    @classmethod
    def is_connected(cls):
        s = socket.socket()
        s.settimeout(3)
        try:
            status = s.connect_ex(('www.baidu.com', 443))
            if status == 0:
                s.close()
                return True
            else:
                return False
        except Exception as e:
            return False


def queue_job():
    if not has_pending_job():
        try:
            requests.get('http://127.0.0.1:8500/spider/start_queue')
        except Exception as e:
            return False
    pass


def has_pending_job():
    response = requests.get('http://127.0.0.1:6800/listjobs.json?project=ContentSpider')
    data = eval(response.text)
    job_list = data['pending']
    if len(job_list) > 0:
        print('has')
        return True
    else:
        print('no')
        return False


if __name__ == '__main__':
    scheduler = BlockingScheduler()
    internet = Adsl()
    # internet.reconnect()AsyncIOScheduler
    # time.sleep(5 * 60)
    scheduler.add_job(internet.reconnect, 'interval', seconds=300)
    scheduler.add_job(queue_job, 'interval', seconds=30)
    print('Press Ctrl+{0} to exit'.format('Break' if os.name == 'nt' else 'C    '))

    try:
        scheduler.start()
    except (KeyboardInterrupt, SystemExit):
        pass
